package com.rc.saas.mini.controller.order;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.charge.ChargeService;
import com.rc.saas.mini.charge.ChargeServiceRouter;
import com.rc.saas.mini.charge.CurrDataFacade;
import com.rc.saas.mini.client.ChargerClientRouter;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.base.TResponse;
import com.rc.saas.mini.common.config.UpYunConfig;
import com.rc.saas.mini.common.constant.HttpConstant;
import com.rc.saas.mini.common.constant.SessionConstants;
import com.rc.saas.mini.hlhtcec2.config.ConvertStatusUtil;
import com.rc.saas.mini.mapper.order.OrderInfoMapper;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.elec.ElecGun;
import com.rc.saas.mini.model.elec.ElecStation;
import com.rc.saas.mini.model.invoice.InvoiceApply;
import com.rc.saas.mini.model.member.MemberAccount;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.order.OrderComment;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.model.order.OrderRefundApply;
import com.rc.saas.mini.service.elec.ElecGunService;
import com.rc.saas.mini.service.elec.ElecStationService;
import com.rc.saas.mini.service.invoice.InvoiceApplyService;
import com.rc.saas.mini.service.member.MemberAccountService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.order.OrderDiscountRecordService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.order.OrderRefundApplyService;
import com.rc.saas.mini.vo.base.RcPageVo;
import com.rc.saas.mini.vo.cec.StdRequest;
import com.rc.saas.mini.vo.charge.CommandCurrDataReq;
import com.rc.saas.mini.vo.charge.CommandStopReq;
import com.rc.saas.mini.vo.invoice.InvoiceApplyWithIdVo;
import com.rc.saas.mini.vo.order.OrderInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单相关功能
 *
 * @author wangzhengwei
 * @create 2021/12/16
 */
@Controller
@RequestMapping("/order")
@Api(tags = "11.订单相关功能")
public class OrderController extends MinipBaseController {
    private static Logger logger = LogManager.getLogger(OrderController.class);
    //B611 电压,B621 电流;C904 SOC,C88D 充电电量,C88E 消费金额,D99E 基本电费,ELEC
    private final String ELEC_B611 = "B611";
    private final String ELEC_B621 = "B621";
    private final String ELEC_C904 = "C904";
    private final String ELEC_C840 = "C840";
    private final String ELEC_C88D = "C88D";
    private final String ELEC_C88E = "C88E";
    private final String ELEC_D88E = "D88E";
    private final String ELEC_E98E = "E98E";
    //private final String ELEC_D99E = "D99E";
    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private OrderDiscountRecordService orderDiscountRecordService;

    @Autowired
    private ChargeService chargeService;

    @Autowired
    private UpYunConfig upYunConfig;


    @Autowired
    private ElecStationService elecStationService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ElecGunService elecGunService;
    @Autowired
    private InvoiceApplyService invoiceApplyService;

    @Autowired
    private OrderRefundApplyService orderRefundApplyService;

    @Autowired
    private ChargerClientRouter chargerClientRouter;

    @Autowired
    private CurrDataFacade currDataFacade;
    @Autowired
    private MemberAccountService memberAccountService;

    /**
     * 获取订单年月列表及当月统计数
     */
    @ResponseBody
    //@RequestMapping("/listOrderYearMonthAndCountCurrMonOrd")
    //@ApiOperation(value = "获取订单年月列表及当月统计数据", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping("/listOrderYearMonth")
    @ApiOperation(value = "获取订单年月列表（不一定使用）", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            //@ApiImplicitParam(name = "yearMonth", paramType = "query", value = "yyyy-MM查询年月", required = true),
            @ApiImplicitParam(name = "accountType", paramType = "query", value = "订单类型(0个人订单 1企业订单 2全部 ，默认2)", required = false),
            @ApiImplicitParam(name = "status", paramType = "query", value = "订单状态(0:全部 1:充电中,2:已完成) 默认0 ", required = false),
            //@ApiImplicitParam(name = "carNumes", paramType = "query", value = "车牌号,多个逗号分割", required = false),
            //@ApiImplicitParam(name = "pageNo", paramType = "query", value = "页码", required = true),
            //@ApiImplicitParam(name = "pageSize", paramType = "query", value = "页量", required = true),
    })
    public DataTResponse<List<String>> listOrderYearMonthAndCountCurrMonOrd(HttpServletRequest request,
                                                                            @RequestParam(value = "status", defaultValue = "0") String status, String yearMonth,
                                                                            @RequestParam(value = "accountType", defaultValue = "2") String accountType, String carNumes, Integer pageNo, Integer pageSize) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        if ("0".equals(status) || "".equals(status)) {
            status = null;
        }
        if ("2".equals(accountType) || "".equals(accountType)) {
            accountType = null;
        }
        logger.info("OrderController.listOrderYearMonthAndCountCurrMonOrd.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
        //OrderStatisticsVo orderStatisticsVo = orderInfoService.countOrderByYearMonth(member, yearMonth);

        //PageInfo<String> page = orderInfoService.listPageYearMonthByMemberId(member.getMemberId(), accountType, carNumes, pageNo, pageSize);
        List<String> list = orderInfoMapper.listYearMonthByMemberId(member.getMemberId(), accountType, null, status);
        //OderYearMonthAndCountCurrMonOrdVo vo = new OderYearMonthAndCountCurrMonOrdVo();
        //vo.setOrderStatisticsVo(orderStatisticsVo);
        //vo.setYearMonthList(page);
        return DataTResponse.SUCCESS_DATA(list);
    }

    /**
     * 根据年月获取订单列表
     */
    @ResponseBody
    @RequestMapping("/listOrderByYearMonth")
    @ApiOperation(value = "根据年月获取订单列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yearMonth", paramType = "query", value = "yyyy-MM查询年月", required = false),
            @ApiImplicitParam(name = "accountType", paramType = "query", value = "订单类型(0个人订单 1企业订单 2全部 ，默认2)", required = false),
            @ApiImplicitParam(name = "status", paramType = "query", value = "订单状态(0:全部 1:充电中,2:已完成) 默认0 ", required = false),
            @ApiImplicitParam(name = "carNumes", paramType = "query", value = "车牌号,多个逗号分割", required = false),
    })
    public DataTResponse<PageInfo<OrderInfoVo>> listOrderByYearMonth(HttpServletRequest request,
                                                                     @RequestParam(value = "status", defaultValue = "0") String status, String yearMonth,
                                                                     @RequestParam(value = "accountType", defaultValue = "2") String accountType, String carNumes, RcPageVo rcPageVo) throws JsonProcessingException {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("OrderController.listOrderByYearMonth.tenantCode:{},mobile:{}", tenantCode, member.getMobile());

        if ("2".equals(accountType) || "".equals(accountType)) {
            accountType = null;
        }
        if ("0".equals(status) || "".equals(status)) {
            status = null;
        }
        PageHelper.startPage(rcPageVo.getPageNo(), rcPageVo.getPageSize());
        List<OrderInfoVo> orderInfoList = orderInfoService.listOrderByYearMonth(member, yearMonth, accountType, carNumes, status);

        if (orderInfoList.size() == 0) {
            return DataTResponse.SUCCESS();
        }
        List<Long> ids = orderInfoList.stream().map(OrderInfoVo::getOrderId).collect(Collectors.toList());
        List<InvoiceApplyWithIdVo> invoiceApplyList = invoiceApplyService.listByOrderIds(ids);
        List<OrderRefundApply> orderRefundApplyList = orderRefundApplyService.listByOrderIds(ids);


        for (OrderInfoVo orderInfoVo : orderInfoList) {

            orderInfoVo.setSurplusTime(chargeService.getRemainChargingTime(orderInfoVo.getOrderNum()));
            orderInfoVo.setOrderRefundApply(orderRefundApplyList.stream().filter(data -> orderInfoVo.getOrderId().equals(data.getOrderId())).findFirst().orElseGet(() -> null));
            orderInfoVo.setInvoiceApplyWithIdVo(invoiceApplyList.stream().filter(data -> orderInfoVo.getOrderId().equals(data.getOrderId())).findFirst().orElseGet(() -> null));
            if ("1".equals(orderInfoVo.getStatus())) {
                try {
                    CommandCurrDataReq commandCurrDataReq = new CommandCurrDataReq();
                    commandCurrDataReq.setTenantCode(orderInfoVo.getTenantCode());
                    commandCurrDataReq.setMemberId(orderInfoVo.getMemberId());
                    commandCurrDataReq.setElecPileId(orderInfoVo.getElecPileId());
                    ElecGun elecGun = elecGunService.selectByPrimaryKey(orderInfoVo.getElecGunId());
                    commandCurrDataReq.setGunNum(elecGun.getGunNum()!=null?elecGun.getGunNum():null);
                    //B611 电压,B621 电流;C904 SOC,C88D 充电电量,C88E 消费金额,D99E 基本电费,ELEC
                    commandCurrDataReq.setCode(new String[]{ELEC_B611, ELEC_B621, ELEC_C904, ELEC_C88D, ELEC_C88E, ELEC_C840, ELEC_D88E, ELEC_E98E});

                    logger.info(tenantCode + ":本次采样入参:{}", commandCurrDataReq.toString());
                    //加密
                    ObjectMapper objectMapper = new ObjectMapper();
                    String respData = objectMapper.writeValueAsString(commandCurrDataReq);
                    String jsonData = encryptData(respData, tenantCode);
                    StdRequest tRequest = genSuccessReq(jsonData, tenantCode);

                    TResponse tResponse = currDataFacade.getCurrDataMap(commandCurrDataReq);
                    Map<String, Object> result = (java.util.Map<String, Object>) tResponse.getData();
                    logger.info(tenantCode + ":本次采样原值:{}:{}", orderInfoVo.getOrderNum(), result);
                    if (result.containsKey(ELEC_C904)) {
                        orderInfoVo.setSoc(result.get(ELEC_C904) == null ? BigDecimal.ZERO
                                : new BigDecimal(String.valueOf(result.get(ELEC_C904))).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }

                    //所充电量
                    if (result.containsKey(ELEC_C88D)) {
                        orderInfoVo.setTotalPower(result.get(ELEC_C88D) == null ? BigDecimal.ZERO
                                : new BigDecimal(String.valueOf(result.get(ELEC_C88D))).setScale(3, BigDecimal.ROUND_HALF_UP));
                    }

                    //消费金额
                    if (result.containsKey(ELEC_C88E)) {
                        orderInfoVo.setTotalMoney(result.get(ELEC_C88E) == null ? new BigDecimal("0")
                                : new BigDecimal(String.valueOf(result.get(ELEC_C88E))).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }

                    //基本电费
                    if (result.containsKey(ELEC_D88E)) {
                        orderInfoVo.setTotalElecMoney(result.get(ELEC_D88E) == null ? new BigDecimal("0")
                                : new BigDecimal(String.valueOf(result.get(ELEC_D88E))).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                    //服务费
                    if (result.containsKey(ELEC_E98E)) {
                        orderInfoVo.setTotalSeviceMoney(result.get(ELEC_E98E) == null ? new BigDecimal("0")
                                : new BigDecimal(String.valueOf(result.get(ELEC_E98E))).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        //if (orderInfoList != null) {
        //    Collections.reverse(orderInfoList);
        //}
        return DataTResponse.SUCCESS_DATA(new PageInfo<>(orderInfoList));
    }

    ///**
    // * 根据年月统计订单
    // */
    //@ResponseBody
    //@RequestMapping("/countOrderByYearMonth")
    //@ApiOperation(value = "根据年月统计订单", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "yearMonth", paramType = "query", value = "yyyy-MM查询年月", required = true),
    //})
    //public TResponse countOrderByYearMonth(@ApiIgnore HttpSession session, String yearMonth) {
    //    String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
    //    if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
    //        logger.error("找不到对应运营商信息:{}", tenantCode);
    //        return TResponse.FAIL("找不到对应运营商信息");
    //    }
    //    LoginInfoVo loginInfo = readLoginInfo(request);
    //    if (loginInfo == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
    //    if (member == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    logger.info("OrderController.countOrderByYearMonth.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
    //
    //    OrderStatisticsVo orderStatisticsVo = orderInfoService.countOrderByYearMonth(member, yearMonth);
    //    return TResponse.SUCCESS_DATA(orderStatisticsVo);
    //}
    //
    ///**
    // * 查找订单列表
    // */
    //@ResponseBody
    //@RequestMapping("/listPageOrder")
    //@ApiOperation(value = "查找订单列表", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "pageNo", paramType = "form", value = "页码", required = true),
    //        @ApiImplicitParam(name = "pageSize", paramType = "form", value = "页量", required = true),
    //        @ApiImplicitParam(name = "startDate", paramType = "query", value = "yyyy-MM-dd hh:mm:ss", required = true),
    //        @ApiImplicitParam(name = "endDate", paramType = "query", value = "yyyy-MM-dd hh:mm:ss", required = true),
    //        @ApiImplicitParam(name = "carNum", paramType = "query", value = "车牌号", required = true),
    //        @ApiImplicitParam(name = "memberType", paramType = "query", value = "会员类型 0个人 1企业", required = true),
    //
    //})
    //public TResponse listPageOrder(@ApiIgnore HttpSession session, Integer pageNo, Integer pageSize, String startDate, String endDate, String carNum, String memberType) {
    //    String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
    //    if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
    //        logger.error("找不到对应运营商信息:{}", tenantCode);
    //        return TResponse.FAIL("找不到对应运营商信息");
    //    }
    //    LoginInfoVo loginInfo = readLoginInfo(request);
    //    if (loginInfo == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
    //    if (member == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    logger.info("OrderController.listPageOrder.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
    //    List<OrderInfo> list = orderInfoService.listPageOrder(pageSize, pageNo, loginInfo.getMemberId(), startDate, endDate, carNum, memberType);
    //    return TResponse.SUCCESS_DATA(list);
    //}


    /**
     * 根据订单ID查找订单
     */
    @ResponseBody
    @RequestMapping("/getOrderById")
    @ApiOperation(value = "根据订单ID查找订单", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", paramType = "query", value = "订单Id", required = true),
    })
    public DataTResponse<OrderInfoVo> getOrderById(HttpServletRequest request, Long orderId) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("OrderController.getOrderById.tenantCode:{},mobile:{}", tenantCode, member.getMobile());

        OrderInfoVo orderInfoVo = orderInfoService.selectOrderById(orderId);
        //List<OrderDiscountRecord> list = orderDiscountRecordService.selectByOrderId(tenantCode, orderId);
        //出场方式
        //ElecStation elecStation = elecStationService.selectByPrimaryKey(orderInfoVo.getElecStationId());
        //ElecGun elecGun = elecGunService.selectByPrimaryKey(orderInfoVo.getElecGunId());
        //ElecStationOutVo elecStationOutVo = chargeService.assembleStationOutData(elecStation, orderInfoVo, elecGun, upYunConfig);
        //
        //Map map = new HashMap();
        //map.put("order", orderInfoVo);
        //map.put("orderDiscountRecordList", list);
        //map.put("elecStationOut", elecStationOutVo);
        //
        //TResponse tResponse = TResponse.SUCCESS();
        //tResponse.put(map);


        List<Long> ids = new ArrayList<>();
        ids.add(orderId);
        List<InvoiceApplyWithIdVo> invoiceApplyList = invoiceApplyService.listByOrderIds(ids);
        List<OrderRefundApply> orderRefundApplyList = orderRefundApplyService.listByOrderIds(ids);
        //剩余充电时间 todo

        orderInfoVo.setSurplusTime(chargeService.getRemainChargingTime(orderInfoVo.getOrderNum()));
        orderInfoVo.setOrderRefundApply(orderRefundApplyList.stream().filter(data -> orderInfoVo.getOrderId().equals(data.getOrderId())).findFirst().orElseGet(() -> null));
        orderInfoVo.setInvoiceApplyWithIdVo(invoiceApplyList.stream().filter(data -> orderInfoVo.getOrderId().equals(data.getOrderId())).findFirst().orElseGet(() -> null));


        return DataTResponse.SUCCESS_DATA(orderInfoVo);
    }

    ///**
    // * 充电中修改车牌号
    // */
    //@ResponseBody
    //@RequestMapping("/updateOrderCarNum")
    //@ApiOperation(value = "充电中修改车牌号(需要登录)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "orderId", paramType = "query", value = "订单ID(orderId,orderNum,outOrderNum 不能同时为空)", required = false),
    //        @ApiImplicitParam(name = "carNum", paramType = "query", value = "车牌号", required = true),
    //        @ApiImplicitParam(name = "orderNum", paramType = "query", value = "订单号(orderId,orderNum,outOrderNum 不能同时为空)", required = false),
    //        @ApiImplicitParam(name = "outOrderNum", paramType = "query", value = "外部订单号(orderId,orderNum,outOrderNum 不能同时为空)", required = false),
    //})
    //public TResponse updateOrderCarNum(@ApiIgnore HttpSession session, Long orderId, String carNum, String orderNum, String outOrderNum) {
    //    String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
    //    if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
    //        logger.error("找不到对应运营商信息:{}", tenantCode);
    //        return TResponse.FAIL("找不到对应运营商信息");
    //    }
    //    LoginInfoVo loginInfo = readLoginInfo(request);
    //    if (loginInfo == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
    //    if (member == null) {
    //        return TResponse.FAIL_LOGIN();
    //    }
    //    logger.info("OrderController.updateOrderCarNum.tenantCode:{},mobile:{},carNum:{},:{},:{},:{}", tenantCode, member.getMobile(), carNum, orderId, orderNum, outOrderNum);
    //
    //    if (StringUtils.isEmpty(carNum)) {
    //        return TResponse.FAIL("车牌号不能为空");
    //    }
    //    if (!carNum.matches(HttpConstant.CAR_NUMBER_REGEX)) {
    //        return TResponse.FAIL("车牌号格式不正确");
    //    }
    //
    //    OrderInfo order = null;
    //    if (orderId != null) {
    //        order = orderInfoService.selectOrderById(orderId);
    //    } else if (StringUtils.isNotEmpty(orderNum)) {
    //        order = orderInfoService.selectOrderByOrderNum(orderNum);
    //    } else if (StringUtils.isNotEmpty(outOrderNum)) {
    //        order = orderInfoService.selectOrderByOutOrderNum(outOrderNum);
    //    }
    //    if (order == null) {
    //        return TResponse.FAIL("不存在订单!");
    //    }
    //
    //    order.setCarNum(carNum);
    //    orderInfoService.updateByPrimaryKeySelective(order);
    //    return TResponse.SUCCESS();
    //}

    /**
     * 执行发送终止充电命令(只发送命令,需检查是否发送成功以及在成功后轮询订单状态)
     */
    @ResponseBody
    @RequestMapping(value = "/updateOrder", method = RequestMethod.POST)
    @ApiOperation(value = "订单结算", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "outOrderNum", paramType = "query", value = "外部订单号", required = true)})
    public DataTResponse<String> updateOrder(HttpServletRequest request, String outOrderNum) {
        //if (StringUtils.isBlank(tenantCode)) {
        //    logger.error("找不到对应运营商信息:{}", tenantCode);
        //    return DataTResponse.FAIL("找不到对应运营商信息");
        //}

        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        String tenantCode = loginInfo.getTenantCode();
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }


        logger.info("updateOrder.tenantCode:{}:mobile:{},outOrderNum:{}", tenantCode, member.getMobile(), outOrderNum);

        OrderInfo orderInfo = orderInfoService.selectOrderByOutOrderNum(outOrderNum);

        if("5".equals(orderInfo.getStatus())){
            return DataTResponse.FAIL("占位中无法结算");
        }

        MemberAccount memberAccount=memberAccountService.selectByPrimaryKey(member.getMemberId());

        if("0".equals(orderInfo.getAccountType())){
            if((memberAccount.getAccount().add(memberAccount.getGiveAccount())).compareTo(orderInfo.getPayAmount())<0){
                return DataTResponse.FAIL("余额不足");
            }
        }



        ElecStation elecStation = elecStationService.selectByPrimaryKey(orderInfo.getElecStationId());
        try {

            //发送指令
            TResponse tResponse = chargerClientRouter.updateOrder(elecStation.getElecServerDomain(), elecStation.getElecServerSpliter(), orderInfo.getOrderId());
            if (tResponse.getStatus() == HttpConstant.STATUS_SUCCESS) {
                logger.info(tenantCode + ":发送订单自动结算成功:{}", outOrderNum);

                //直接返回,不再执行以下的停充指令
                //stopChargeResult.setStartChargeSeqStat(4);//已结束
                return DataTResponse.SUCCESS();
            } else {
                logger.error(tenantCode + ":发送订单自动结算失败:{}", outOrderNum);
                //stopChargeResult.setStartChargeSeqStat(5); //未知

                //直接返回,不再执行以下的停充指令
                //stopChargeResult.setFailReason(5);//自定义失败原因:上次订单还没结算完，请稍等(这个错误码只有瑞晨有)
                //return stopChargeResult;
                return DataTResponse.FAIL("处理失败");
            }

        } catch (Exception e) {
            logger.error("发送结算命令失败", e);
            return DataTResponse.FAIL("处理失败");
        }

    }


    /**
     * 根据订单ID查找订单
     */
    @ResponseBody
    @RequestMapping("/deleteOrderById")
    @ApiOperation(value = "根据订单ID删除订单", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", paramType = "query", value = "订单Id 开票，退款的无法删除", required = true),
    })
    public DataTResponse<String> deleteOrderById(HttpServletRequest request, Long orderId) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        OrderInfoVo orderInfo=orderInfoService.selectOrderById(orderId);



        if(orderInfo!=null){

            List<Long> ids = new ArrayList<>();
            ids.add(orderId);
            List<InvoiceApplyWithIdVo> invoiceApplyList = invoiceApplyService.listByOrderIds(ids);
            List<OrderRefundApply> orderRefundApplyList = orderRefundApplyService.listByOrderIds(ids);

            orderInfo.setOrderRefundApply(orderRefundApplyList.stream().filter(data -> orderInfo.getOrderId().equals(data.getOrderId())).findFirst().orElseGet(() -> null));
            orderInfo.setInvoiceApplyWithIdVo(invoiceApplyList.stream().filter(data -> orderInfo.getOrderId().equals(data.getOrderId())).findFirst().orElseGet(() -> null));
            if(orderInfo.getOrderRefundApply()!=null&&"0".equals(orderInfo.getOrderRefundApply().getStatus())){
                return DataTResponse.FAIL("该订单退款审核中，暂不能删除~");
            }
            if(orderInfo.getInvoiceApplyWithIdVo()!=null&&"0".equals(orderInfo.getInvoiceApplyWithIdVo().getStatus())){
                return DataTResponse.FAIL("该订单开票审核中，暂不能删除~");
            }
            orderInfo.setIsDelete("1");
            orderInfo.setLastUpdatedTime(new Date());
            orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
            return DataTResponse.SUCCESS();
        }

        return DataTResponse.FAIL("删除失败");
    }
}
